package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

import lib.Subject;
import lib.persistence.ExcelConnector;
import lib.persistence.NotFoundException;
import lib.persistence.ProjectFactory;
import lib.persistence.commands.MakeCSV;
import lib.validation.Message;
import lib.validation.ValidationHandler;
import models.Project;
import views.Main;

public class MainController 
	extends ControllerAbstract 
{

	private Main bsc;
	Project p;
	public MainController() throws NotFoundException, SQLException, IOException, ClassNotFoundException
	{
		registerController();
		bsc = new Main();
	    bsc.setVisible(true);
	    
	    
	    mapProjectsToView();

	    getView().getBtOpenProject().addActionListener(getOpenProjectActionListener());
	    getView().btQuit.addActionListener(getQuitAction());
	    getView().btUploadFile.addActionListener(getUploadFileActionListener());
	    getView().getBtCreateReport().addActionListener(alGenerateReport());
	}
	private ActionListener alGenerateReport() 
	{
		return new java.awt.event.ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				Project p;
				try {
					p = Project.find(getSelectedProjectId());
					MakeCSV mcsv = new MakeCSV();
					mcsv.makeProjectReport(Project.findAll());
					mcsv.makeDeliverableReport(p.getDeliverables());
				} catch (Exception e1) 
				{
					e1.printStackTrace();
				}
				
			}
		};
	}
	private ActionListener getOpenProjectActionListener() 
	{
		return new java.awt.event.ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				try {
					
					ProjectController pController = new ProjectController(Project.find(getSelectedProjectId()));
					pController.addObserver((MainController) global.ControllerRegistry.getInstance().getControllerByShortName("MainController"));
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}

		};
	}
	private int getSelectedProjectId() {
		String projectTitle = (String) getView().getLiPeople().getModel().getElementAt(getView().getLiPeople().getSelectedIndex());
		String[] splitArray = projectTitle.split("\\:");
		return Integer.parseInt(splitArray[0]);
	}
	private void mapProjectsToView() throws SQLException, IOException, ClassNotFoundException {
		List<Project> projects = Project.findAll();
		DefaultListModel model = new DefaultListModel();	    	    
	    
		for (int i = 0; i < projects.size(); i++) 
			model.add(i, String.format("%s: %s",projects.get(i).getId() ,projects.get(i).getName()));
	    
	    bsc.getLiPeople().setModel(model);
	}
	public Main getView()
	{
		return bsc;
	}
	public ValidationHandler uploadFileAction(String filePath)
	{
		ValidationHandler vh = new ValidationHandler();
	    File f = new File(filePath);
	    if (!f.exists())
	    {
	    	vh.addMessage(new Message("File not found!", false));
	    	return vh;
	    }
	    try {
	    	ExcelConnector ec = new ExcelConnector(filePath);
			ProjectFactory pf = new ProjectFactory(ec);
			pf.getProjects();
		} catch (Exception e1) {			
			vh.addMessage(new Message("import failed: \n "+e1.getStackTrace(),false));
		}

	    vh.addMessage(new Message("Project succesfully imported!",true));
	    return vh;
	    	
	}
	public ActionListener getUploadFileActionListener()
	{
		return new java.awt.event.ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				try {
					MainController mc = (MainController) global.ControllerRegistry.getInstance().getControllerByShortName("MainController");
					final JFileChooser fc = new JFileChooser();
					int returnVal = fc.showOpenDialog(getView());
			        if (returnVal == JFileChooser.APPROVE_OPTION) {
			            File file = fc.getSelectedFile();
						ValidationHandler vld = mc.uploadFileAction(file.getAbsolutePath());

						if (vld.isValid())
							JOptionPane.showMessageDialog(null,"Success! \n" + vld.getMessages().get(0).getMessage());						

						else
							JOptionPane.showMessageDialog(null, "Something bad happened! \n"+ vld.getMessages().get(0).getMessage());

						try {
							mapProjectsToView();
						} catch (Exception e1) 
						{
							e1.printStackTrace();
						}
			        } 
					
				    
				} catch (NotFoundException e1) {
					e1.printStackTrace();
				}
			
			}
		};
	}
	public ActionListener getQuitAction() {
		return new java.awt.event.ActionListener() 
	    {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{
				System.exit(0);
			}
		};
	}
	@Override
	public String getShortName() {
		return "MainController";
	}
	@Override
	// refresh the view!
	public void update(Subject o) {
		if (o instanceof ProjectController)
		{
			try {
				mapProjectsToView();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
}
